package com.aaa.ssm.controller;

import com.aaa.ssm.entity.User;
import com.aaa.ssm.service.UserService;
import com.aaa.ssm.util.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@RestController
@RequestMapping("l")
public class LoginController extends BaseController {
    @Resource //依赖注入
    private UserService userService;

    @Resource
    private HttpServletResponse response;
    /**
     * 登录方法
     * @param
     * @param session
     * @return
     */
    @PostMapping("login") //Cookie是客户端技术 不是十分安全 只能存储 String 类型的对象   session是服务端技术---任何类型 能够存储任意的 java 对象
    public Result login(String userName,String passWord, HttpSession session) {
        User user = new User();
        user.setUserName(userName);
        user.setPassword(passWord);
        System.out.println("user =---------------------------------------------  " + user);
        User user1 = userService.checkUser(user);
        System.out.println("user1 =--------------------------------------------- " + user1);
        int userId =  user1.getUserId();
        String loginNameA = user1.getLoginName();
        session.setAttribute("userA", userId);
        if (user1 != null) {
            session.setAttribute("userInfo",user1);
            session.setAttribute("loginA", loginNameA);
            session.setAttribute("nameA", loginNameA);
            return success(user1);
        } else {
            return error(user1);
        }
    }

    /**
     * 为前端传输登录的姓名
     * @param session
     * @return
     */
    @GetMapping("getLoginSession")
    public Result getLoginSession11(HttpSession session) {
        return success(session.getAttribute("userInfo"));
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @PostMapping("logout")
    public void logout(HttpSession session) throws IOException {
        session.removeAttribute("loginA");
        session.removeAttribute("userInfo");
        session.removeAttribute("userA");
        session.invalidate();
    }

    /**
     * 修改密码
     * @param password
     * @param session
     * @return
     */
    @PostMapping("updatePw/{password}")
    public Result updatePw(@PathVariable("password")String password,HttpSession session) {
        String loginA = (String) session.getAttribute("loginA");
        System.out.println("loginA = " + loginA);
        System.out.println("password = " + password);
        User user = new User();
        user.setLoginName(loginA);
        user.setPassword(password);
        return success(userService.updatePw(user));
    }
}
